package com.topcheer.provider.auth.rest;

import com.topcheer.common.base.vo.BaseResponse;
import com.topcheer.provider.auth.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.topcheer.provider.auth.jwt.vo.JwtAuthenticationRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xutao
 * @Package com.topcheer.provider.auth.rest
 * @Description: ${todo}
 * @date 2020/4/8 9:19
 */
@RestController
@RequestMapping("jwt")
@Slf4j
public class AuthController {

    @Autowired
    AuthService authService;


    @Value("${jwt.token-header}")
    private String tokenHeader;

    @PostMapping(value = "/token")
    public BaseResponse<Map> createToken(@RequestBody JwtAuthenticationRequest jwtAuthenticationRequest) throws Exception {
        String token = authService.login(jwtAuthenticationRequest);
        Map<String,String> result = new HashMap<>();
        result.put(tokenHeader,token);
        return new BaseResponse<Map>().data(result);
    }



    @RequestMapping(value = "/refresh", method = RequestMethod.GET)
    public BaseResponse<String> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        return new BaseResponse<String>().data(refreshedToken);
    }
}
